﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections.ObjectModel;
using BBEverNote.ViewModels;
using Thrift;
using Thrift.Protocol;
using Thrift.Server;
using Thrift.Transport;
using Evernote.EDAM.Type;
using Evernote.EDAM.UserStore;
using Evernote.EDAM.NoteStore;
using Evernote.EDAM.Error;

namespace BBEverNote.Models
{
    public class ENNoteBookModel : ViewModelBase
    {
        public ENNoteBookModel()
        {

        }

        string _enGuid;

        public string EnGuid
        {
            get { return _enGuid; }
            set 
            {
                _enGuid = value;
                OnPropertyChanged("EnGuid");
            }
        }

        string _name;

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        bool? _isChecked = false;

        public bool? IsChecked
        {
            get { return _isChecked; }
            set
            { 
                SetIsChecked(value, true, true); 
            }
        }

        void SetIsChecked(bool? value, bool updateChildren, bool updateParent)
        {
            if (value == _isChecked)
                return;

            _isChecked = value;

            if (updateChildren && _isChecked.HasValue)
            {
                this.SubNoteBooks.ToList().ForEach(c => c.SetIsChecked(_isChecked, true, false));
            }

            if (updateParent && _parent != null)
            {
                _parent.VerifyCheckState();
            }

            OnPropertyChanged("IsChecked");
        }

        void VerifyCheckState()
        {
            bool? state = null;
            for (int i=0; i<SubNoteBooks.Count; i++)
            {
                bool? current = SubNoteBooks[i].IsChecked;
                if (i == 0)
                {
                    state = current;
                }
                else if (state != current)
                {
                    state = null;
                    break;
                }
            }
            SetIsChecked(state, false, true);
        }

        ENNoteBookModel _parent = null;

        public ENNoteBookModel ParentNote
        {
            get { return _parent; }
            set 
            { 
                _parent = value;
                OnPropertyChanged("Parent");
            }
        }


        ObservableCollection<ENNoteBookModel> _subNoteBooks = new ObservableCollection<ENNoteBookModel>();

        public ObservableCollection<ENNoteBookModel> SubNoteBooks
        {
            get { return _subNoteBooks; }
            set
            {
                _subNoteBooks = value;
                OnPropertyChanged("SubNoteBooks");
            }
        }

    }
}
